package 力扣._200_岛屿数量;

public class Solution {

    int[][] visited;

    //深度优先
    void dfs(char[][] grid, int i, int j) {  //从（i,j）开始遍历
        visited[i][j] = 1;
        //上
        if (i - 1 >= 0 && grid[i - 1][j] == '1' && visited[i - 1][j] == 0)
            dfs(grid, i - 1, j);
        //下
        if (i + 1 < grid.length && grid[i + 1][j] == '1' && visited[i + 1][j] == 0)
            dfs(grid, i + 1, j);
        //左
        if (j - 1 >= 0 && grid[i][j - 1] == '1' && visited[i][j - 1] == 0)
            dfs(grid, i, j - 1);
        //右
        if (j + 1 < grid[0].length && grid[i][j + 1] == '1' && visited[i][j + 1] == 0)
            dfs(grid, i, j + 1);
    }

    public int numIslands(char[][] grid) {
        //深度优先搜索，带标记数组，有几个不连通极大连通分量，就有几个岛屿
        visited = new int[grid.length][grid[0].length];
        int sum = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1' && visited[i][j] == 0) {
                    dfs(grid, i, j);
                    sum++;
                }
            }
        }
        return sum;
    }
}
